package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.oms.core.utils.IdGenerator;
import com.lsh.oms.core.utils.http.HttpClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: RefundProxy
 * 北京链商电子商务有限公司
 * Auth: wangliutao
 * Date: 18/6/8
 * Package Name: com.lsh.oms.core.proxy.service
 * Description:调用商城的退款接口,申请退款
 *
 * @author peter
 */
@Service
@Slf4j
public class RefundProxy {
    private static final String REFUND_URL = "/refund/order/apply";

    @Value("${mis.host}")
    private String shopUrl;

    public JSONObject refund(Long orderCode, Integer cancelType, Long venderId, Map<String, Object> moreParams) {
        JSONObject params = new JSONObject(moreParams);
        params.put("order_id", orderCode);
        params.put("type", cancelType.toString());

        log.info("[request payment param json is ] {}", params.toJSONString());

        Map<String, String> head = new HashMap<>(6);
        head.put("api-version", "1.1");
        head.put("sign", String.valueOf(IdGenerator.genId()));
        head.put("platform", "oms");
        head.put("venderId", venderId + "");
        try {
            String requestBody = params.toJSONString();

            log.info("[ {} - requestBody is ] {} ", orderCode, requestBody);
            String response = HttpClientTemplate.doPost(shopUrl + REFUND_URL, params, head);

            log.info("[ {} - response is ] {}", orderCode, response);
            if (StringUtils.isNotBlank(response)) {
                return JSON.parseObject(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
